package edu.utexas.mapreduce;


import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class HttpPingHandler implements HttpHandler {
	
	// SS: local view of sState
	private SharedMapState sState = null;
	
	// SS: constructor
	public HttpPingHandler(SharedMapState sharedState) {
		this.sState = sharedState;
	}

	// SS: extract the jobId from the URL input string
	private static int getJobId(String url) {
		int jobId = 0;
		
		// scan the input for the jobId using the ? delimiter, this 
		// will allow for acquiring the jobId from the URL
		Scanner query = new Scanner(url);
		query.useDelimiter("\\?");
		
		// extract the jobId from the input string
		while (query.hasNext()) {
			if (query.hasNextInt()) {
				// get the jobId and convert to integer
				String tmp = query.next();	
				jobId = Integer.parseInt(tmp);
				break;
			}
			query.next();
		}
		return jobId;
	}

	
	// SS: ping status to detect of jobId is in map, does this need to 
	//     be moved into the sState?
	private String status(String urlQuery) {		
		int job = getJobId(urlQuery);
		if (0 == job) {
			// invalid input
			System.out.println("Invalid input = " + job);
			return "JOB UNKNOWN";
		}
		else {
			// get the thread from the shared object
			JobThread jThread = sState.getJobThread(job);
			if ((null != jThread) && (jThread.isAlive())) {
				return "OK";  // job exists and is running...
			}
		}
		return "JOB NOT RUNNING";
	}
	
	
	public void handle(HttpExchange httpEx) throws IOException {
		
		//SS: changes to allow for job status ping
		String tmp      = httpEx.getRequestURI().toString();
		String response = status(tmp);
		
		System.out.println("HTTP ping request " + httpEx.getRequestURI().getQuery() + ": " + response);
		
	    httpEx.sendResponseHeaders(200, response.length());
        OutputStream os = httpEx.getResponseBody();
        os.write(response.getBytes());
        os.close();
	}
}
	
	
